<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@ page import="java.util.List" %>
<%@ page import="java.util.Date" %>
<%@ page import= "java.text.SimpleDateFormat" %>
<%@ page import="com.google.appengine.api.users.User" %>
<%@ page import="com.google.appengine.api.users.UserService" %>
<%@ page import="com.google.appengine.api.users.UserServiceFactory" %>
<%@ page import="com.google.appengine.api.datastore.DatastoreServiceFactory" %>
<%@ page import="com.google.appengine.api.datastore.DatastoreService" %>
<%@ page import="com.google.appengine.api.datastore.Query" %>
<%@ page import="com.google.appengine.api.datastore.Entity" %>
<%@ page import="com.google.appengine.api.datastore.FetchOptions" %>
<%@ page import="com.google.appengine.api.datastore.Key" %>
<%@ page import="com.google.appengine.api.datastore.KeyFactory" %>

<html>

  <body>

    <form action="/applications.jsp" method="get">
      <div><input type="text" name="appName" value="TestApp"/></div>
      <div><input type="submit" value="Get data" /></div>
    </form>
<%
	String appName = request.getParameter("appName");
	SimpleDateFormat simpleDateFormat = new SimpleDateFormat("dd.MM.yyyy HH:mm:ss");
    if (appName != null) {
        DatastoreService datastore = DatastoreServiceFactory.getDatastoreService();
        Key appHostKey = KeyFactory.createKey("ApplicationHost", appName);
        Query query = new Query("ApplicationHost", appHostKey).addSort("date", Query.SortDirection.DESCENDING);
        List<Entity> appHosts = datastore.prepare(query).asList(FetchOptions.Builder.withLimit(5));

	    if (!appHosts.isEmpty()) {
%>
		<p>Last AppHosts for '<%= appName %>'.</p>
		<%
			for (Entity appHost : appHosts) {
	        	
	        	String ip4Address = (String)appHost.getProperty("ip4Address");
	        	String port = (String)appHost.getProperty("port");
	        	Date date = (Date)appHost.getProperty("date");
		%>
				<p><%=ip4Address%>:<%=port%> from: <i><%= simpleDateFormat.format(date) %></i></p>
		<%
	        }
		%>
<%
	    }
    
	}
%>



  </body>
</html>
